package beans;

import java.util.Collection;

import org.hibernate.Query;
import org.hibernate.Session;

/**
 * 分页查询对象(java bean),用来包装分页查询条件并构造查询语句.
 * @param <T> 分页查询返回的记录类型
 * @author spring
 */
public abstract class AbstractPagedQuery<T> {
    /**
     * 默认一页显示的记录数.
     */
    private static final int DEFAULT_ITEMS_PERPAGE = 20;

    /**
     * 查询的结果集合.
     */
    private Collection<T> queryResults;

    /**
     * 查询结果,总共条目个数.
     */
    private long totalCount = -1;

    /**
     * 分页条件:一页的记录条数.
     */
    private int itemsPerPage = DEFAULT_ITEMS_PERPAGE;

    /**
     * 查询条件:查询起始纪录位置.
     */
    private int pagerOffset;

    /**
     * @return Returns the itemsPerPage.
     */
    public int getItemsPerPage() {
        return itemsPerPage;
    }

    /**
     * 这个方法只在在AbstractPagedQueryAction中调用
     * @param pItemsPerPage The itemsPerPage to set.
     */
    public void setItemsPerPage(int pItemsPerPage) {
        this.itemsPerPage = pItemsPerPage;
    }

    /**
     * @return Returns the queryResults.
     */
    public Collection<T> getQueryResults() {
        return queryResults;
    }

    /**
     * @param pQueryResults The queryResults to set.
     */
    public void setQueryResults(Collection<T> pQueryResults) {
        this.queryResults = pQueryResults;
    }

    /**
     * @return Returns the totalCount.
     */
    public long getTotalCount() {
        return totalCount;
    }

    /**
     * @param pTotalCount The totalCount to set.
     */
    public void setTotalCount(long pTotalCount) {
        this.totalCount = pTotalCount;
    }

    /**
     * 检查页码是否是有效.
     */
    public void checkPagerOffset() {

        boolean valid = (this.pagerOffset >= 0 && pagerOffset <= totalCount);
        if (!valid) {
            pagerOffset = 0;
        }
    }

    /**
     * 设置查询纪录的起始位置.
     * @param pPagerOffset The pagerOffset to set.
     */
    public void setPagerOffset(int pPagerOffset) {
        this.pagerOffset = pPagerOffset;
    }

    /**
     * @return Returns the pagerOffset.
     */
    public int getPagerOffset() {
        return pagerOffset;
    }

    /**
     * 构造Hibernate Query 对象. 如果queryTotalCount=true则构造查询总数的(sql)
     * Query,否则,构造查询指定范围纪录的(sql) Query
     * @param session Hibernate Session
     * @param isQueryTotalCount 是否构造查询总数的(sql) Query
     * @return Query
     */
    public abstract Query buildQuery(Session session, boolean isQueryTotalCount);
}
